package com.aidex.web.controller.api;

import cn.hutool.json.JSONUtil;
import com.aidex.biz.domain.Order;
import com.aidex.biz.service.JdKuaiyunService;
import com.aidex.biz.service.OrderService;
import com.aidex.biz.service.QingYangOrderService;
import com.aidex.biz.service.WxPayService;
import com.aidex.common.config.AiDexConfig;
import com.aidex.common.core.controller.BaseController;
import com.aidex.common.core.domain.entity.Company;
import com.aidex.common.utils.StringUtils;
import com.aidex.common.utils.sms.ChuangLanSmsClient;
import com.aidex.system.service.CompanyService;
import com.alibaba.fastjson.JSONObject;
import com.wechat.pay.contrib.apache.httpclient.util.AesUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付回调
 *
 * @author sean
 * @email 2074844820@qq.com
 * @date 2022-09-21
 */
@RestController("ApiWxPayController")
@RequestMapping("/api/wxpay")
@Api(tags = "小程序首页管理接口")
@Component
public class WxPayCallBackController extends BaseController {


    @Autowired
    private CompanyService companyService;
    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private OrderService orderService;
    @Autowired
    private QingYangOrderService qingYangOrderService;

    @Autowired
    private JdKuaiyunService jdKuaiyunService;

    private static final Logger log = LoggerFactory.getLogger(WxPayCallBackController.class);
    /**
     * 微信支付回调
     */
    @PostMapping("/callBack")
    public Map<String, String> callBack(@RequestBody JSONObject jsonObject) {
        try {
            Company company = companyService.get(AiDexConfig.getCompanyId());
            String key = company.getWechatMchKey();
            String json = jsonObject.toString();
            String associated_data = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.associated_data");
            String ciphertext = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.ciphertext");
            String nonce = (String) JSONUtil.getByPath(JSONUtil.parse(json), "resource.nonce");
            String decryptData =
                    new AesUtil(key.getBytes(StandardCharsets.UTF_8)).decryptToString(associated_data.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
            //验签成功
            JSONObject decryptDataObj = JSONObject.parseObject(decryptData, JSONObject.class);
            //decryptDataObj 为解码后的obj，其内容如下。之后便是验签成功后的业务处理
            String orderId = decryptDataObj.getString("out_trade_no");
            Order order = orderService.get(orderId);
            Company shopCompany=companyService.get(order.getCompanyId());
            // 支付成功
            if ("SUCCESS".equals(decryptDataObj.getString("trade_state"))) {
                order.setWxPayNo(decryptDataObj.getString("transaction_id"));
                order.setStatus("0");
                // 支付成功 如果是洗护订单 推送轻氧订单
                if ("0".equals(order.getOrderType())){
                    JSONObject qyJsonObject= qingYangOrderService.pushQingYangOrder(order);
                    if("200".equals(qyJsonObject.getString("code"))){
                        order.setQingyangOrderId(qyJsonObject.getJSONObject("data").getString("qingyangOrderNumber"));
                        //  如果是平台订单 推送京东订单
                        if(order.getCompanyId().equals(AiDexConfig.getCompanyId())){
                            String deliverNo=orderService.pushJdKuaiYun(order);
                            order.setDeliveryNo(deliverNo);
                        }else{
                            String deliverNo="YJK"+StringUtils.Getnum();
                            order.setDeliveryNo(deliverNo);
                            // 修改氢氧单号
                            qingYangOrderService.modifyDeliveryNumber(order);
                        }
                    }
                    ChuangLanSmsClient.sendSms(shopCompany.getLianxiPhone(),
                            "您有新的洗护订单，请打开《优洁客》微信小程序查看");
                }else{
                    ChuangLanSmsClient.sendSms(shopCompany.getLianxiPhone(),
                            "您有新的商城订单，请打开《优洁客》微信小程序查看");
                }
            }
            // 没有支付
            if ("NOTPAY".equals(decryptDataObj.getString("trade_state"))) {
                order.setStatus("-1");
            }
            order.setPayDate(new Date());
            order.setPayStatus(1);
            orderService.save(order);
                   //{
            //	"sp_appid": "wx8888888888888888",
            //	"sp_mchid": "1230000109",
            //	"sub_appid": "wxd678efh567hg6999",
            //	"sub_mchid": "1900000109",
            //	"out_trade_no": "1217752501201407033233368018",
            //	"trade_state_desc": "支付成功",
            //	"trade_type": "MICROPAY",
            //	"attach": "自定义数据",
            //	"transaction_id": "1217752501201407033233368018",
            //	"trade_state": "SUCCESS",
            //	"bank_type": "CMC",
            //	"success_time": "2018-06-08T10:34:56+08:00",
            //    ...
            //	"payer": {
            //		"openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
            //	},
            //	"scene_info": {
            //		"device_id": "013467007045764"
            //	}
            //}
        } catch (Exception e) {
            log.error("{} ,parms{}, 异常:", jsonObject.toJSONString(), e);
        }

        Map<String, String> res = new HashMap<>();
        res.put("code", "SUCCESS");
        res.put("message", "成功");
        return res;
    }
}






